package phone.example.com.a36kr.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import phone.example.com.a36kr.R;
import phone.example.com.a36kr.activity.NewsSecondActivity;
import phone.example.com.a36kr.activity.SearchActivity;
import phone.example.com.a36kr.adapter.CollectLvAdapter;
import phone.example.com.a36kr.adapter.KrTvLvAdapter;
import phone.example.com.a36kr.adapter.NewsViewPagerAdapter;
import phone.example.com.a36kr.adapter.newslistviewadapter.NewsAdapter;
import phone.example.com.a36kr.bean.KrTvBean;
import phone.example.com.a36kr.bean.NewsBean;
import phone.example.com.a36kr.bean.NewsCarouselBean;
import phone.example.com.a36kr.bean.UrlBean;
import phone.example.com.a36kr.main.MainActivity;
import phone.example.com.a36kr.nettool.NetTool;
import phone.example.com.a36kr.other.swiperefreshlayout.MySwipeRefreshLayout;
import phone.example.com.a36kr.tools.BaseFragment;
import phone.example.com.a36kr.tools.MyApp;


/**
 * Created by dllo on 16/8/15.
 */
public class NewsFragment extends BaseFragment {


    private ListView lv;
    private NewsAdapter newsAdapter;// ListViewAdapter

    private ArrayList<String> arrayList;//轮播图集合
    private NewsViewPagerAdapter viewPagerAdapter;//轮播图适配器
    private View mView;//轮播图 布局
    private NewsBean newsBean;

    //listView 两条url
    private String url = "https://rong.36kr.com/api/mobi/news?pageSize=";
    private int page = 1;
    private String urlTwo = "&columnId=";
    private String urlThree = "all&pagingAction=up";
//    private String urlTwo = "https://rong.36kr.com/api/mobi/news?pageSize=40&columnId=all&pagingAction=up";

    // 轮播图url
    private String imgUrl = "https://rong.36kr.com/api/mobi/roundpics/v4";
    private ViewPager viewPager;
    private MySwipeRefreshLayout mSwipeRefreshLayout;


    // 轮播图的线程
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            Message message = handler.obtainMessage();
            message.what = 1;
            handler.sendMessageDelayed(message, 5000);
            return false;
        }
    });
    private TextView newsTitleTv;
    private NewsBroadcastReceiver nesReceiver;
    private LinearLayout dropLl;// 轮播图小点

    @Override
    protected int setLayout() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {
        newsTitleTv = bindView(R.id.fragment_news_title_tv);
        ImageView searchIm = bindView(R.id.news_search_im);
        searchIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);

            }
        });

        // 下拉刷新组件ID
        mSwipeRefreshLayout = (MySwipeRefreshLayout) getView().findViewById(R.id.fragment_news_srl);
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        lv = bindView(R.id.fragment_news_lv);
        viewPagerAdapter = new NewsViewPagerAdapter(MyApp.getContext());
        mView = LayoutInflater.from(getContext()).inflate(R.layout.news_items_carousel, null);
        viewPager = bindView(mView, R.id.news_items_VP);
        newsAdapter = new NewsAdapter(getContext());// 新闻页 ListViewAdapter

        ImageView navigationIn = bindView(R.id.navigation_iv);
        navigationIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.openMenu();
            }
        });


    }

    private ImageView[] imageViews;

    @Override
    protected void initData() {
        newsBean = new NewsBean();
        // 轮播图的集合
        arrayList = new ArrayList<>();
        //解析ListView数据
        initNet();

        //*****************iniNet(); 是 ListView数据,下是轮播图数据********************************//
        mNetTool.getNetData(imgUrl, NewsCarouselBean.class, new NetTool.NetListener<NewsCarouselBean>() {

            private ImageView imageView;//new 出来的image

            @Override
            public void onSuccess(NewsCarouselBean newsCarouselBean) {
                for (int i = 0; i < newsCarouselBean.getData().getPics().size(); i++) {
                    arrayList.add(newsCarouselBean.getData().getPics().get(i).getImgUrl());
                    // 新建个image
                    imageView = new ImageView(getContext());
                    imageView.setImageResource(R.mipmap.dian);
                }

                imageViews = new ImageView[newsCarouselBean.getData().getPics().size()];//圆点数量

                viewPagerAdapter.setmList(arrayList);
                viewPagerAdapter.setViewPager(viewPager);
                //给listview添加头布局
                lv.addHeaderView(mView);
                viewPager.setAdapter(viewPagerAdapter);

            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(mContext, "无法获取图片", Toast.LENGTH_SHORT).show();
            }
        });


        //**********************************下拉刷新***********************************/
        /**
         * 下拉刷新
         * OnRefreshListener下拉刷新实现的方法
         */
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                lv.setAdapter(null);
                //解析listView数据
                initNet();
                mSwipeRefreshLayout.setRefreshing(false);


            }
        });
        //**************************************上拉加载********************************/

        mSwipeRefreshLayout.setOnLoadListener(new MySwipeRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                page++;
                NetTool netTool = new NetTool();
                netTool.getNetData(url + (page * 20) + urlTwo + urlThree, NewsBean.class, new NetTool.NetListener<NewsBean>() {
                    @Override
                    public void onSuccess(final NewsBean newsBean) {
                        newsAdapter.setNewsBean(newsBean);
                        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getActivity(), NewsSecondActivity.class);
                                String mFeedId = new String(newsBean.getData().getData().get(position - lv.getHeaderViewsCount()).getFeedId());
                                Log.d("NewsFragment", mFeedId);
                                intent.putExtra("newsFeedId", mFeedId);
                                startActivity(intent);
                            }
                        });

                        mSwipeRefreshLayout.setLoading(false);

                    }

                    @Override
                    public void onError(String errorMsg) {
                        Log.d("NewsFragment", "数据获取失败");

                    }
                });
            }
        });


    }

    private void initNet() {
        mNetTool = new NetTool();
        mNetTool.getNetData(url + (page * 20) + urlTwo + urlThree, NewsBean.class, new NetTool.NetListener<NewsBean>() {
            @Override
            public void onSuccess(final NewsBean newsBean) {
                newsAdapter.setNewsBean(newsBean);
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(getActivity(), NewsSecondActivity.class);
                        String mFeedId = new String(newsBean.getData().getData().get(position - lv.getHeaderViewsCount()).getFeedId());
                        Log.d("NewsFragment", mFeedId);
                        intent.putExtra("newsFeedId", mFeedId);
                        startActivity(intent);
                    }
                });
                lv.setAdapter(newsAdapter);

            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(mContext, "数据请求失败,请检查网络连接", Toast.LENGTH_SHORT).show();
            }
        });

    }


    // 轮播图线程的生命周期
    @Override
    public void onStart() {
        super.onStart();
        Log.d("NewsFragment", "start");
        Message message = handler.obtainMessage();
        message.what = 1;
        handler.sendMessageDelayed(message, 5000);

        // 广播接收器
        nesReceiver = new NewsBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.36kr.android.newsReplaceUrl");
        getActivity().registerReceiver(nesReceiver, filter);


    }

    @Override
    public void onStop() {
        super.onStop();
        handler.removeMessages(1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(nesReceiver);
    }

    /********************
     * 抽屉 点击筛选的方法 *
     ********************/
    public class NewsBroadcastReceiver extends BroadcastReceiver {
        //判断抽屉 在哪一页
        private boolean header = false;

        @Override
        public void onReceive(Context context, Intent intent) {

            final String newsReplaceUrl = intent.getStringExtra("newsReplaceUrl");
            urlThree = intent.getStringExtra("newsSelectUrl");
            if (UrlBean.NEWS_KRTY_URL.equals(newsReplaceUrl)) {
                mNetTool.getNetData(UrlBean.NEWS_KRTY_URL, KrTvBean.class, new NetTool.NetListener<KrTvBean>() {
                    @Override
                    public void onSuccess(KrTvBean krTvBean) {
                        KrTvLvAdapter tvAdapter = new KrTvLvAdapter(getContext());
                        tvAdapter.setKrTvBean(krTvBean);
                        lv.setAdapter(tvAdapter);
                        lv.removeHeaderView(mView);
                    }

                    @Override
                    public void onError(String errorMsg) {

                    }
                });

            } else {

                //将网址传到适配器里
                newsAdapter.setNewsReplaceUrl(newsReplaceUrl);
                mNetTool.getNetData(newsReplaceUrl, NewsBean.class, new NetTool.NetListener<NewsBean>() {
                    @Override
                    public void onSuccess(NewsBean newsBean) {
                        newsAdapter.setNewsBean(newsBean);
                        //equals 判断字符串的方法
                        if (newsReplaceUrl.equals(UrlBean.NEWS_ALL_URL)) {
                            //如果header为true
                            // 那么就是从别的页点回来的,需要添加头布局,
                            // 并重设header 为false
                            if (header == true) {
                                // lv.addHeaderView(mView);
                                //显示头布局
                                viewPager.setVisibility(viewPager.VISIBLE);
                                header = false;
                            }
                        } else {
                            // 删除头布局
                            // lv.removeHeaderView(mView);
                            //隐藏头布局
                            viewPager.setVisibility(viewPager.GONE);
                            header = true;
                        }
                        lv.setAdapter(newsAdapter);
                    }

                    @Override
                    public void onError(String errorMsg) {
                        Toast.makeText(mContext, "数据请求失败,请检查网络连接", Toast.LENGTH_SHORT).show();
                    }
                });


                if (UrlBean.NEWS_ALL_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("全部");
                } else if (UrlBean.NEWS_EPROJECT_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("早期项目");
                } else if (UrlBean.NEWS_BWHEEL_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("B轮后");
                } else if (UrlBean.NEWS_BCOMPANY_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("大公司");
                } else if (UrlBean.NEWS_CAPITAL_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("资本");
                } else if (UrlBean.NEWS_DEPTH_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("深度");
                } else if (UrlBean.NEWS_STUDY_URL.equals(newsReplaceUrl)) {
                    newsTitleTv.setText("研究");
                } else {
                    newsTitleTv.setText("氪KV");
                }
            }

        }
    }

}
